import {
    _decorator,
    Color,
    color,
    Component,
    instantiate,
    Label,
    Node,
    Prefab,
    ScrollView,
    SpriteFrame,
    tween,
    UITransform,
    Vec3
} from 'cc';
import {GameMain} from "./GameMain";
import Platform, {PlatformType} from "./Platform";
import {LevelSelItem} from "./LevelSelItem";
import {Tip} from "./Tip";

const { ccclass, property } = _decorator;

@ccclass('StartGameUI')
export class StartGameUI extends Component
{
    @property({type:SpriteFrame})
    levelCurrentSpriteFrame:SpriteFrame=null;

    @property({type:SpriteFrame})
    levelPassedSpriteFrame:SpriteFrame=null;

    @property({type:SpriteFrame})
    levelLockedSpriteFrame:SpriteFrame=null;

    @property({type:[SpriteFrame]})
    diffSpriteFrames:Array<SpriteFrame>=[];

    @property({type:Prefab})
    levelSelItemPrefab:Prefab=null;

    private dailyAwardBtnNode:Node=null;
    private redPoint:Node=null;

    private settingBtnNode:Node=null;
    private shareBtnNode:Node=null;
    private rankBtnNode:Node=null;
    private xieyiBtnNode:Node=null;

    private moreGameBtnNode:Node=null;

    private addDesktopBtnNode:Node=null;

    public scroll:ScrollView=null;
    public scrollContentUITrans:UITransform=null;

    public attachNode:Node=null;

    //开始游戏按钮
    public startGameBtnNode:Node=null;

    public hpLabel:Label=null;
    public moneyLabel:Label=null;
    public starLabel:Label=null;
    public moneySpriteNode:Node=null;

    public bottomNode:Node=null;
    public level0AnchorNode:Node=null;

    public topCityLabel:Label=null;

    public hpTimeLabel:Label=null;

    public inited:boolean=false;

    public static readonly greenLineColor:Color=color(119, 216, 123, 255);
    public static readonly grayLineColor:Color=color(162, 162, 162, 255);

    onLoad()
    {
        this.init();
    }

    start() {
        this.initUI();
        Platform.createInsertAd();
        if(Platform.currentPlatform===PlatformType.WECHAT)
        {
            this.startGameBtnNode.setPosition(0, 335, 0);
            this.moreGameBtnNode.active=false;
            this.rankBtnNode.active=true;
        }
        else
        {
            this.startGameBtnNode.setPosition(0, 500, 0);
        }

        if(Platform.currentPlatform===PlatformType.ANDROID)
        {
            this.moreGameBtnNode.active=true;
        }
        else
        {
            this.moreGameBtnNode.active=false;
        }

        if(Platform.isOV())
        {
            this.addDesktopBtnNode.active=true
        }
        else
            this.addDesktopBtnNode.active=false;
    }

    public init()
    {
        let topNode:Node=this.node.getChildByName("top");
        this.dailyAwardBtnNode=topNode.getChildByName("dailyAwardBtn");
        this.redPoint=this.dailyAwardBtnNode.getChildByName("redPoint");

        this.moreGameBtnNode=topNode.getChildByName("moreGameBtn");
        this.addDesktopBtnNode=topNode.getChildByName("addDesktopBtn");

        this.topCityLabel=topNode.getChildByName("topCity").getChildByName("cityLabel").getComponent(Label);

        this.settingBtnNode=topNode.getChildByName("settingBtn");
        this.shareBtnNode=topNode.getChildByName("shareBtn");
        this.rankBtnNode=topNode.getChildByName("rankBtn");
        this.xieyiBtnNode=topNode.getChildByName("xieyiBtn");

        this.scroll=this.node.getChildByName("ScrollView").getComponent(ScrollView);
        this.scrollContentUITrans=this.scroll.content.getComponent(UITransform);
        this.attachNode=this.scroll.content.getChildByName("attach");

        this.startGameBtnNode=this.node.getChildByName("bottom").getChildByName("startBtn");
        this.startGameBtnNode.active=false;

        this.bottomNode=this.node.getChildByName("bottom");
        this.level0AnchorNode=this.bottomNode.getChildByName("level0Anchor");

        let topUINode:Node=topNode.getChildByName("topUI");
        this.hpLabel=topUINode.getChildByName("hpBar").getChildByName("Label").getComponent(Label);
        this.hpTimeLabel=topUINode.getChildByName("hpBar").getChildByName("timeLabel").getComponent(Label);
        this.moneyLabel=topUINode.getChildByName("moneyBar").getChildByName("Label").getComponent(Label);
        this.moneySpriteNode=topUINode.getChildByName("moneyBar").getChildByName("scale").getChildByName("icon");
        this.starLabel=topUINode.getChildByName("starBar").getChildByName("Label").getComponent(Label);
        this.inited=true;
    }

    public initUI()
    {
        if(!this.inited)
            this.init();

        this.initLevels();
        this.updateUI();
        this.initScrollPosition();

        this.scheduleOnce(()=>{
            this.startFadeInUI();
        }, 0.3);
    }

    public showTopCity()
    {
        if(GameMain.instance.topCity!=="")
        {
            this.topCityLabel.string=GameMain.instance.topCity;

            let targetNode:Node=this.topCityLabel.node.parent;
            targetNode.active=true;
            targetNode.setScale(0.2, 0.2, 1);
            tween(targetNode).to(0.45, {scale: Vec3.ONE}, {easing: "backOut"}).call(() =>
            {
            }).start();
        }
    }

    //根据当前关卡设置起始position
    public initScrollPosition()
    {
        let curLevelId:number=GameMain.instance.gameData.curLevelId;
        let levelSelItemComponent:LevelSelItem=null;
        let curLevelItemComponent:LevelSelItem=null;
        for(let i=0;i<this.attachNode.children.length;i++)
        {
            levelSelItemComponent=this.attachNode.children[i].getComponent("LevelSelItem");
            if(levelSelItemComponent.levelId===curLevelId)
            {
                curLevelItemComponent=levelSelItemComponent;
                break;
            }
        }

        if(curLevelItemComponent!==null)
        {
            let levelItemUITrans:UITransform=curLevelItemComponent.node.getComponent(UITransform);
            let worldPos:Vec3=levelItemUITrans.convertToWorldSpaceAR(Vec3.ZERO);
            let anchorLocalPos:Vec3=this.level0AnchorNode.getComponent(UITransform).convertToNodeSpaceAR(worldPos);

            let contentPos:Vec3=this.scroll.content.getPosition();
            contentPos.y-=anchorLocalPos.y;
            contentPos.y+=100;
            this.scroll.content.setPosition(contentPos);
        }
    }

    //自动滚动到当前levelItem
    public scrollToCurLevelItem()
    {
        let curLevelId:number=GameMain.instance.gameData.curLevelId;
        let levelSelItemComponent:LevelSelItem=null;
        let curLevelItemComponent:LevelSelItem=null;
        for(let i=0;i<this.attachNode.children.length;i++)
        {
            levelSelItemComponent=this.attachNode.children[i].getComponent("LevelSelItem");
            if(levelSelItemComponent.levelId===curLevelId)
            {
                curLevelItemComponent=levelSelItemComponent;
                break;
            }
        }

        if(curLevelItemComponent!==null)
        {
            let levelItemUITrans:UITransform=curLevelItemComponent.node.getComponent(UITransform);
            let worldPos:Vec3=levelItemUITrans.convertToWorldSpaceAR(Vec3.ZERO);
            let anchorLocalPos:Vec3=this.level0AnchorNode.getComponent(UITransform).convertToNodeSpaceAR(worldPos);

            let contentPos:Vec3=this.scroll.content.getPosition();
            contentPos.y-=anchorLocalPos.y;
            contentPos.y+=125;

            tween(this.scroll.content).to(0.75, { position: contentPos}).call(()=>{

            }).start();
        }
    }

    public initLevels()
    {
        let levelSelItem:LevelSelItem=null;

        //计算需要显示的起始levelid,0-5都是0开始,6开始减末尾元素
        let curLevelId:number=GameMain.instance.gameData.curLevelId;

        console.log("***** curLevelID="+curLevelId);

        for(let i=0;i<40;i++)
        {
            let obj=instantiate(this.levelSelItemPrefab);
            this.attachNode.addChild(obj);
            levelSelItem=obj.getComponent("LevelSelItem");
            levelSelItem.setLevel(curLevelId+i);
            obj.setPosition(0, 600+i*300,0);
        }

        for(let i=0;i<4;i++)
        {
            let levelId:number=curLevelId - (i+1);
            if(levelId<0)
                break;
            let obj=instantiate(this.levelSelItemPrefab);
            this.attachNode.addChild(obj);
            levelSelItem=obj.getComponent("LevelSelItem");
            levelSelItem.setLevel(levelId);
            obj.setPosition(0, 600 - (i+1)*300,0);
            obj.setSiblingIndex(0);
        }

        //计算scroll content 高度
        this.scrollContentUITrans.height=40*300;
    }

    public updateLevelItems()
    {
        //移除最开始的item
        let item0:Node=this.attachNode.children[0];
        let levelSelItem:LevelSelItem=item0.getComponent("LevelSelItem");
        if(GameMain.instance.gameData.curLevelId - levelSelItem.levelId >= 5)
        {
            item0.removeFromParent(true);
            item0.destroy();
        }

        let childrenLen:number=this.attachNode.children.length;
        let lastItem:LevelSelItem=this.attachNode.children[childrenLen-1].getComponent("LevelSelItem");

        //末尾添加新item
        let obj=instantiate(this.levelSelItemPrefab);
        this.attachNode.addChild(obj);
        levelSelItem=obj.getComponent("LevelSelItem");
        levelSelItem.setLevel(lastItem.levelId + 1);

        let pos:Vec3=lastItem.node.getPosition();
        pos.y+=300;
        obj.setPosition(pos);

        pos=this.attachNode.getPosition();
        pos.y-=300;
        this.attachNode.setPosition(pos);
    }

    public debugPring()
    {
        console.log("** content pos="+JSON.stringify(this.scroll.content.getPosition()));

        //level 节点位置
        let levelItemUITrans:UITransform=this.scroll.content.children[0].getComponent(UITransform);
        let worldPos:Vec3=levelItemUITrans.convertToWorldSpaceAR(Vec3.ZERO);
        console.log("** level node worldpos="+JSON.stringify(worldPos));

        levelItemUITrans=this.scroll.content.children[1].getComponent(UITransform);
        worldPos=levelItemUITrans.convertToWorldSpaceAR(Vec3.ZERO);
        console.log("** level node1 worldpos="+JSON.stringify(worldPos));

        console.log("** node 1 pos="+ JSON.stringify(this.scroll.content.children[0].getPosition()));

        let anchorWorldPos:Vec3=this.level0AnchorNode.getComponent(UITransform).convertToWorldSpaceAR(Vec3.ZERO);
        console.log("** anchorWorldPos ="+JSON.stringify(anchorWorldPos));

        let contentPos:Vec3=this.scroll.content.getPosition();
        contentPos.y-=worldPos.y - anchorWorldPos.y;
        this.scroll.content.setPosition(contentPos);

    }

    public updateUI()
    {
        this.updateRedPoint();

        this.updateHpLabel();
        this.updateMoneyLabel();
        this.updateStarLabel();

        let levelSelItemComponent:LevelSelItem=null;
        for(let i=0;i<this.attachNode.children.length;i++)
        {
            levelSelItemComponent=this.attachNode.children[i].getComponent("LevelSelItem");
            levelSelItemComponent.updateBgSprite();
        }

        if(Platform.isOV() || Platform.currentPlatform===PlatformType.TT || Platform.isAndroid())
        {
            if(Platform.isOV() || Platform.isAndroid())
                this.xieyiBtnNode.active=true;
            else
                this.xieyiBtnNode.active=false;
            this.shareBtnNode.active=false;
            //this.rankBtnNode.active=false;
        }
        else
        {
            this.xieyiBtnNode.active=false;
            this.shareBtnNode.active=true;
            //this.rankBtnNode.active=false;
        }
    }

    public updateRedPoint()
    {
        let canGetAward:boolean=GameMain.instance.dailyAwardUI.checkAwardTime();
        this.redPoint.active=canGetAward;
    }

    public updateHpLabel()
    {
        this.hpLabel.string="" + GameMain.instance.gameData.hp;
    }

    public updateMoneyLabel()
    {
        this.moneyLabel.string="" + GameMain.instance.gameData.money;
    }

    public updateStarLabel()
    {
        this.starLabel.string="" + GameMain.instance.gameData.star;
    }

    public show()
    {
        this.updateUI();
        this.node.active=true;

        this.scheduleOnce(()=>{
            this.startFadeInUI();
        }, 0.75);

    }

    public startFadeInUI()
    {
        //scale current level node
        let curLevelId:number=GameMain.instance.gameData.curLevelId;
        let levelSelItemComponent:LevelSelItem=null;
        let curLevelItemComponent:LevelSelItem=null;
        for(let i=0;i<this.attachNode.children.length;i++)
        {
            levelSelItemComponent=this.attachNode.children[i].getComponent("LevelSelItem");
            if(levelSelItemComponent.levelId===curLevelId)
            {
                curLevelItemComponent=levelSelItemComponent;
                break;
            }
        }

        if(curLevelItemComponent!==null)
        {
            curLevelItemComponent.scaleAnim();
        }

        this.scrollToCurLevelItem();

        this.startGameBtnNode.active=false;
        this.scheduleOnce(()=>{
            this.startGameBtnNode.active=true;
            this.startGameBtnNode.setScale(0.3, 0.3, 1);
            tween(this.startGameBtnNode).to(0.5, {scale:Vec3.ONE },{easing:"backOut"}).call(()=>{

            }).start();
        }, 0.6);
    }

    public close()
    {
        this.node.active=false;
    }

    public onStartGameClicked()
    {
        /*
        //体力扣除和检测
        if(GameMain.instance.gameData.hp>=1)
            GameMain.instance.addHp(-1);
        else
        {

            //体力不足
            GameMain.instance.hpNotEnoughUI.show();
            return;

        }*/

        let levelsLen:number=GameMain.levelCfg.length;

        if(GameMain.instance.gameData.curLevelId>=levelsLen)
        {
            //显示即将更新提升
            Tip.show();
            return;
        }
        else
        {
            this.scheduleOnce(()=>{
                this.close();
            }, 0.3);
            GameMain.instance.startGame();
        }
    }

    public addHpClicked()
    {
        GameMain.instance.hpNotEnoughUI.show();
    }

    public onXieyiClicked()
    {
        GameMain.instance.agreementUI.showYinsiUI();
    }

    update(deltaTime: number) {
        
    }
}

